import { onBeforeUnmount, onMounted, ref } from "vue"
import { awaitTime, getValueByModel, setValueByModel } from "../util"
import { logInfo } from "../log"

const warpSplit = "\r";
const enterSplit = "\n";
const colSplitCode = '\t'
const rowSplitCode = '\r'

export const usePaste = function (
    SelectState: SelectCellStateResult, 
    currentView: CurrentViewResult, 
    props: Props
) {

    onMounted(() => { document.addEventListener('keydown', keydownHandel) })
    onBeforeUnmount(() => document.removeEventListener('keydown', keydownHandel))

    function keydownHandel(e: KeyboardEvent){
        if (!currentView.checkCurrentView()) return;
        if ((e?.ctrlKey || e?.metaKey) && e?.keyCode == 86) {
            pasteHandel()
        }
    }

    async function pasteHandel() {

        const text: string  = await ClipboardTocopyTextFallback();
        const data: (string | unknown[])[] = text.split(rowSplitCode);
        
        data.forEach((item, index) => {
            data[index] = (item as string).split(colSplitCode);
        })

        const { startX, endX, startY, endY } = SelectState.selectCellState.value
        let minX = Math.min(startX!, endX!)
        let minY = Math.min(startY!, endY!)
        const { columns, dataSource } = props;

        logInfo('将要复粘贴的内容：', text)
        for ( const rowValue of data ){
            if (minY > dataSource.length - 1) {
                // 加入新行
                props.dataSource.push({ })
            }
            for(const colValue of rowValue) {
                if (minX <= columns.length - 1) {
                    const { dataIndex, options, type } = columns[minX];

                    /**
                     * 执行粘贴
                     * 
                     */

                    // 配置了选项
                    if (options) {
                        // 多选
                        if (type === 'checkbox') {
                            const value = colValue?.split?.(',').map((str: string) => options.find(item => item.label === str)?.value ?? str)
                            setValueByModel(dataIndex, props.dataSource[minY], value)
                        } 
                        // 单选
                        else {
                            const value = options.find(item => item.label === colValue)?.value ?? colValue
                            setValueByModel(dataIndex, props.dataSource[minY], value)
                        }
                    } 
                    else {
                        setValueByModel(dataIndex, props.dataSource[minY], colValue)
                    }
                    
                    // 数据类型转换 todo
                    //...
                } 
                else {
                    break;
                }
                minX++;
            }
            minY++;
            minX = Math.min(startX!, endX!)
        }

    }


    async function ClipboardTocopyTextFallback(): Promise<string> {
        const currentActiveElement: Element | null = document.activeElement

        try {

            const text = await navigator.clipboard.readText();
            return text.replace(new RegExp(enterSplit, 'g'), warpSplit);

        } catch (e) {

            const textarea = document.createElement("textarea");
            textarea.setAttribute('style', 'opacity: 0; height: 1px;');
            textarea.setAttribute('readonly', 'readonly');
            document.body.appendChild(textarea);
            textarea.setSelectionRange(0, 999999);
            textarea.select();
            
            awaitTime(0);

            const text = textarea.value.replace(new RegExp(enterSplit, 'g'), warpSplit);
            document.body.removeChild(textarea);

            return text;

        } finally {
            // @ts-ignore
            currentActiveElement?.select?.();
        }
    }

    return { pasteHandel }
}